package top.waikin.mooc.portal.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.waikin.mooc.common.exception.CacheException;
import top.waikin.mooc.common.service.RedisService;
import top.waikin.mooc.entity.User;
import top.waikin.mooc.portal.service.UserCacheService;

@Service
public class UserCacheServiceImpl implements UserCacheService {

    @Autowired
    RedisService redisService;

    @Value("${redis.database}")
    private String REDIS_DATABASE;
    @Value("${redis.expire.common}")
    private Long REDIS_EXPIRE;
    @Value("${redis.expire.authCode}")
    private Long REDIS_EXPIRE_AUTH_CODE;
    @Value("${redis.key.user}")
    private String REDIS_KEY_USER;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_AUTH_CODE;

    @Override
    public void saveUser(User user) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_USER + ":" + user.getTelephone();
        redisService.set(key, user, REDIS_EXPIRE);
    }

    @Override
    public void deleteUser(String telephone) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_USER + ":" + telephone;
        redisService.del(key);
    }

    @Override
    public User getUser(String telephone) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_USER + ":" + telephone;
        return (User) redisService.get(key);
    }

    @CacheException
    @Override
    public void saveAuthCode(String telephone, String authCode) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone;
        redisService.set(key, authCode, REDIS_EXPIRE_AUTH_CODE);
    }

    @CacheException
    @Override
    public String getAuthCode(String telephone) {
        String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone;
        return (String) redisService.get(key);
    }
}
